package com.base.api.pubg.httpclient;

import com.alibaba.fastjson.JSON;
import com.base.api.pubg.enums.PUBG;
import com.base.api.pubg.enums.SERVER;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 请求客户端
 *
 * @author junw
 * @date 2018/5/12
 */
public abstract class BaseHttpClient implements PUBGApi {

    /**
     * 服务器CODE
     */
    private String serverCode = SERVER.PC_AS.getServerName();

    public String getServerCode() {
        return serverCode;
    }

    public void setServerCode(String serverCode) {
        this.serverCode = serverCode;
    }

    /**
     * GET请求API获取JSON
     *
     * @param url 请求地址
     * @return JSONObject
     */
    public Object requestApi(String url) throws IOException {
        return request(new StringBuffer(PUBG.COMPUTED_URL.getDesc()).append(serverCode).append(url).toString());
    }

    /**
     * GET请求获取JSON
     *
     * @param url 请求地址
     * @return JSONObject
     */
    public Object request(String url) throws IOException {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + PUBG.APPID.getDesc());
            conn.setRequestProperty("Accept", "application/vnd.api+json");
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return JSON.parse(convertStreamToString(conn.getInputStream()));
            } else {
                return JSON.parse(convertStreamToString(conn.getErrorStream()));
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * 获取HTTP请求的Json数据
     *
     * @param is 输入流
     * @return Json字符
     */
    private String convertStreamToString(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}
